package kandl.automation.spring.config;

import kandl.automation.http.BasicAuthHttpRequestFactory;

import org.apache.http.HttpHost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;


@Configuration
public class HttpClientConfig {
    @Value("${urlFetcher.timeoutInMillisToObtainConnectionFromConnectionMgr}")
    int connectionTimeout;
    @Value("${request.timeout.in.millis}")
    int readTimeout;
    @Value("${urlFetcher.maxTotalConnections}")
    int maxTotalConnections;
    @Value("${urlFetcher.maxConnectionsPerHost}")
    int defaultMaxConnectionsPerRoute;

    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory() throws Exception {
        BasicAuthHttpRequestFactory factory = new BasicAuthHttpRequestFactory();
        factory.setConnectTimeout(connectionTimeout);
        factory.setReadTimeout(readTimeout);
        factory.setMaxTotalConnections(maxTotalConnections);
        factory.setDefaultMaxConnectionsPerRoute(defaultMaxConnectionsPerRoute);
        factory.setUserName(System.getProperty("testrail.user"));
        factory.setPassword(System.getProperty("testrail.password"));

        factory.init();

        if (useProxy()) {
            HttpHost proxy = new HttpHost(proxyHost(), proxyPort());
            factory.getHttpClient().getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        return factory;
    }

    private boolean useProxy() {
        return proxyHost() != null; // System.getProperty("kl.usingJetty", "false").equalsIgnoreCase("true");
    }

    private String proxyHost() {
        return System.getProperty("https.proxyHost");
    }

    private Integer proxyPort() {
        return Integer.valueOf(System.getProperty("https.proxyPort"));
    }

}

